
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车案例</title>
    <style>
        .plus,.reduce{
            cursor: pointer;
            display: inline-block;
            border: 1px solid #ccc;
            text-align: center;
            position: relative;
            top: 3px;
            width: 20px;height: 20px;
        }
        p input{
            width: 46px;
        }
    </style>
</head>
<body>
    <div>
        <p class="frult">苹果 单价 <span class="jg">5</span>元 数量：
            <input type="number" value="0">
            <span class="plus">+</span>
            <span class="reduce">-</span>
        </p>
        <p class="frult">梨子 单价 <span class="jg">6</span>元 数量：
            <input type="number" value="0">
            <span class="plus">+</span>
            <span class="reduce">-</span>
        </p>
        <p class="frult">橙子 单价 <span class="jg">8</span>元 数量：
            <input type="number" value="0">
            <span class="plus">+</span>
            <span class="reduce">-</span>
        </p>
        <p>水果总数
            <input type="number" disabled class="totality">
            水果总价
            <input type="number" disabled style="width: 100px;" class="price">
        </p>
    </div>
    <script>
        let jg = document.querySelectorAll('.frult .jg')
        let num = document.querySelectorAll('.frult input')
        let plus= document.querySelectorAll('.plus')
        let reduce= document.querySelectorAll('.reduce')
        let totality = document.querySelector('.totality')
        let price = document.querySelector('.price')
        let sum1 = 0;let sum2 = 0
        function total(){
            function sums() {
                sum1 = 0;sum2 = 0
                for(let j=0;j<num.length;j++){
                    sum2 += +jg[j].textContent * +num[j].value
                    sum1 +=  +num[j].value
                    console.log(sum2);
                }
                totality.value = sum1
                price.value = sum2
            }
            plus.forEach((li,i)=>{
                li.onclick=()=>{
                    let singular = +num[i].value+1
                    num[i].value = singular
                    sums()
                }
            })
            reduce.forEach((li,i)=>{
                li.onclick=()=>{
                    let singular = +num[i].value-1
                    if(singular<0){
                        singular = 0    
                    }
                    num[i].value = singular
                    sums()
                }
            })
            num.forEach((li,i)=>{
                li.oninput=()=>{
                    sums()
                }
            })
        }
        total()


    </script>
</body>
</html>